package com.across.connect.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.IllegalAddException;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.across.connect.model.MyUser;
import com.across.connect.util.CommonConst;
import com.across.connect.util.EmailHashUtil;

public class UserXmlParser {

	private static final String xmlfile = CommonConst.DB_USER_XML;
	//private static final String xmlfile = "/opt/swimming-across/user.xml";

	public static Document getRoot() throws JDOMException, IOException {
		SAXBuilder builder = new SAXBuilder();
		InputStream file = new FileInputStream(xmlfile);
		Document document = builder.build(file);
		return document;
	}

	@SuppressWarnings("unchecked")
	public static void XmlParse() throws JDOMException, IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		for (Element e : list) {
			System.out.println("ID=" + e.getAttributeValue("id"));
			System.out.println("username=" + e.getChildText("username"));
			System.out.println("password=" + e.getChildText("password"));
			System.out.println("name=" + e.getChildText("name"));
			System.out.println("email=" + e.getChildText("email"));
			System.out.println("emailhash=" + e.getChildText("emailhash"));
			System.out.println("xnuid="+ e.getChildText("xnuid"));
		}
	}

	public static int addPersonXml(MyUser user) throws JDOMException,
			FileNotFoundException, IOException, IllegalAddException {

		Document document;
		Element root;

		File myFilePath = new File(xmlfile);
		if (!myFilePath.exists()) {
			myFilePath.createNewFile();
			root = new Element("user");
			document = new Document(root);
			XMLOutputter XMLOut = new XMLOutputter();
			XMLOut.output(document, new FileOutputStream(xmlfile));
		} else {
			SAXBuilder builder = new SAXBuilder();
			InputStream file = new FileInputStream(xmlfile);
			document = builder.build(file);
			root = document.getRootElement();
		}
		
		Element element = new Element("person");
		int maxid = getMaxId();
		element.setAttribute("id", String.valueOf(++maxid));

		Element element1 = new Element("username");
		element1.setText(user.getUserName());

		Element element2 = new Element("password");
		element2.setText(user.getPassword());

		Element element3 = new Element("email");
		element3.setText(user.getEmail());

		Element element4 = new Element("name");
		element4.setText(user.getName());

		Element element5 = new Element("emailhash");
		element5.setText(user.getEmailHash());
		
		Element element6 = new Element("xnuid");
		element6.setText(String.valueOf(user.getXnuid()));

		element.addContent(element1);
		element.addContent(element2);
		element.addContent(element3);
		element.addContent(element4);
		element.addContent(element5);
		element.addContent(element6);

		root.addContent(element);
		document.setRootElement(root);

		Format format = Format.getCompactFormat();
		format.setIndent("    ");
		XMLOutputter XMLOut = new XMLOutputter(format);

		XMLOut.output(document, new FileOutputStream(xmlfile));
		return maxid;

	}

	@SuppressWarnings("unchecked")
	public static void deletePerson(int id) throws JDOMException, IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		for (Element e : list) {
			if (Integer.parseInt(e.getAttributeValue("id")) == id) {
				getRoot().removeContent(e);
				break;
			}
		}
		XMLOutputter out = new XMLOutputter();
		out.output(getRoot(), new FileOutputStream(xmlfile));
	}

	@SuppressWarnings("unchecked")
	public static int getMaxId() throws JDOMException, IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		List<Integer> idlist = new ArrayList<Integer>();
		for (Element e : list) {
			idlist.add(Integer.parseInt(e.getAttributeValue("id")));
		}
		Comparator comp = new Comparator() {
			public int compare(Object o1, Object o2) {
				int p1 = (Integer) o1;
				int p2 = (Integer) o2;
				if (p1 < p2)
					return 1;
				else
					return 0;
			}
		};
		Collections.sort(idlist, comp);
		if (idlist.size() > 0) {
			return idlist.get(0);
		}
		return 0;
	}

	@SuppressWarnings("unchecked")
	public static MyUser getPerson(String username, String pwd)
			throws JDOMException, IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		MyUser person = null;
		for (Element e : list) {
			if (username.equals(e.getChildText("username"))
					&& pwd.equals(e.getChildText("password"))) {
				person = new MyUser();
				person.setId(Integer.valueOf(e.getAttributeValue("id")));
				person.setEmail(e.getChildText("email"));
				person.setName(e.getChildText("name"));
				person.setUserName(e.getChildText("username"));
				person.setEmailHash(e.getChildText("emailhash"));
				if (!"".equals(e.getChildText("xnuid"))) {
					person.setXnuid(Integer.parseInt(e.getChildText("xnuid")));
				}
				break;
			}
		}
		return person;
	}

	@SuppressWarnings("unchecked")
	public static MyUser getPersonByUserid(int userid) throws JDOMException,
			IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		MyUser person = null;
		for (Element e : list) {
			if (Integer.parseInt(e.getAttributeValue("id")) == userid) {
				person = new MyUser();
				person.setId(Integer.valueOf(e.getAttributeValue("id")));
				person.setEmail(e.getChildText("email"));
				person.setName(e.getChildText("name"));
				person.setUserName(e.getChildText("username"));
				person.setEmailHash(e.getChildText("emailhash"));
				if (!"".equals(e.getChildText("xnuid"))) {
					person.setXnuid(Integer.parseInt(e.getChildText("xnuid")));
				}
				break;
			}
		}
		return person;
	}
	
	@SuppressWarnings("unchecked")
	public static MyUser getPersonByXiaoneiUID(int uid) throws JDOMException,
			IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		MyUser person = null;
		for (Element e : list) {
			if ("".equals(e.getChildText("xnuid"))) {
				continue;
			}
			if (Integer.parseInt(e.getChildText("xnuid")) == uid) {
				person = new MyUser();
				person.setId(Integer.valueOf(e.getAttributeValue("id")));
				person.setEmail(e.getChildText("email"));
				person.setName(e.getChildText("name"));
				person.setUserName(e.getChildText("username"));
				person.setEmailHash(e.getChildText("emailhash"));
				person.setXnuid(Integer.parseInt(e.getChildText("xnuid")));
				break;
			}
		}
		return person;
	}

	@SuppressWarnings("unchecked")
	public static MyUser getMyUserByEmailHash(String emailhash) throws JDOMException,
			IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		MyUser person = null;
		for (Element e : list) {
			if (emailhash.equals(e.getChildText("emailhash"))) {
				person = new MyUser();
				person.setId(Integer.valueOf(e.getAttributeValue("id")));
				person.setEmail(e.getChildText("email"));
				person.setName(e.getChildText("name"));
				person.setUserName(e.getChildText("username"));
				person.setEmailHash(e.getChildText("emailhash"));
				if (!"".equals(e.getChildText("xnuid"))) {
					person.setXnuid(Integer.parseInt(e.getChildText("xnuid")));
				}
				break;
			}
		}
		return person;
	}

	@SuppressWarnings("unchecked")
	public static boolean isHaveUserName(String username) throws JDOMException,
			IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		for (Element e : list) {
			if (username.equals(e.getChildText("username"))) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static boolean isHaveEmail(String email, String emailhash) throws JDOMException,
			IOException {
		List<Element> list = getRoot().getRootElement().getChildren();
		for (Element e : list) {
			if (email.equals(e.getChildText("email")) || emailhash.equals(e.getChildText("emailhash"))) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	public static void updateMyUser(MyUser user) throws JDOMException,
			IOException {
		Document document = getRoot();
		Element root = document.getRootElement();
		List<Element> list = root.getChildren();
		for (Element e : list) {
			if (Integer.parseInt(e.getAttributeValue("id")) == user.getId()) {
				e.getChild("username").setText(user.getUserName());
				e.getChild("password").setText(user.getPassword());
				e.getChild("email").setText(user.getEmail());
				e.getChild("name").setText(user.getName());
				e.getChild("emailhash").setText(user.getEmailHash());
				e.getChild("xnuid").setText(user.getXnuid()+"");
				break;
			}
		}
		XMLOutputter out = new XMLOutputter();
		out.output(document, new FileOutputStream(xmlfile));
	}

}
